#include "GameGoodsManager.h"
#include "WorldPacket.h"
#include "OpcodesEx.h"
#include "GameDefine.h"
#include "Character.h"
#include "CharManager.h"
#include "WSSocket.h"
#include "WSSocketManager.h"
#include "ItemModelManager.h"
#include "Items.h"
#include "ItemManager.h"
#include "AIInterface.h"
#include "Tools.h"
#include "CenterBankManager.h"
#include "VipCardManager.h"
#include "Message.h"
#include "GameDefine.h"
#include ENUM_PATH
#include LOGIC_MGR_PATH
#include PROTOCOLS_MGR_PATH
#include XMLDATA_MGR_PATH
#include LOG_MGR_PATH

using namespace AIScript;
GameGoodsManager::GameGoodsManager(void)
{
}

GameGoodsManager::~GameGoodsManager(void)
{

}

void GameGoodsManager::load(void)
{
	WGS_GOODSMGR_INNER_LOCK
	m_goodsList.clear();
	sItemMgr.getGoodsListDB(&m_goodsList, 0, 5000,"");
	Log.Debug("GameGoodsManager Test","Load Goods!! Size[%u]", m_goodsList.size());
}

void GameGoodsManager::Reload()
{
	load();
}

const GameGoods* GameGoodsManager::GetGameGoods(const uint32 & model_id, const GoodsFlagDef & buy_type)
{
	WGS_GOODSMGR_INNER_LOCK
	std::list<GameGoods>::iterator ii, endii = m_goodsList.end();
	for(ii = m_goodsList.begin(); ii != endii; ++ ii)
	{
		if((*ii).model_id == model_id && (*ii).flag & buy_type)
			return &*ii;
	}
	
	return NULL;
}

const GameGoods * GameGoodsManager::GetGameGoodsById(const uint32 & goodsId)
{
	WGS_GOODSMGR_INNER_LOCK
	std::list<GameGoods>::iterator ii, endii = m_goodsList.end();
	for(ii = m_goodsList.begin(); ii != endii; ++ ii)
	{
		if((*ii).goods_id == goodsId)
			return &*ii;
	}
	
	return NULL;
}

bool GameGoodsManager::GetGameGoodsById(const uint32 goodsId, GameGoods &goods)
{
	WGS_GOODSMGR_INNER_LOCK
	std::list<GameGoods>::iterator iter, endii = m_goodsList.end();
	for(iter = m_goodsList.begin(); iter != endii; ++iter)
	{
		if((*iter).goods_id == goodsId)
		{
			goods = *iter;
			return true;
		}
	}
	return false;
}

uint32 GameGoodsManager::GetGoodsPrice(const uint32 & model_id, const GoodsFlagDef & buy_type)
{
	WGS_GOODSMGR_INNER_LOCK
	std::list<GameGoods>::iterator ii, endii = m_goodsList.end();
	for(ii = m_goodsList.begin(); ii != endii; ++ ii)
	{
		if((*ii).model_id == model_id && (*ii).flag & buy_type)
			return (*ii).price;
	}
	
	return 0;
}

uint8 GameGoodsManager::GetGoodsList(std::list<GameGoods*> *pGoodsList, const uint8 shopType, const uint32 supId, const uint8 labelType, const uint8 page, const uint8 number)
{
	if (page == 0)
		return 0;
	WGS_GOODSMGR_INNER_LOCK
	uint8 allPage = 0;
	uint32 lowerLimit = (page - 1) * number;
	uint32 upperLimit = lowerLimit + number;
	std::list<GameGoods*> lstTempGoods;
	std::list<GameGoods>::iterator iter, iterEnd = m_goodsList.end();
	for(iter = m_goodsList.begin(); iter != iterEnd; ++iter)
	{
		if (shopType == en_ShopT_GoldShop) // 元宝商城
		{
			if (labelType == en_AT_RealObject)
				return 0;
			if (labelType == (*iter).type && (supId == (*iter).sup_id || 0 == (*iter).sup_id))
				lstTempGoods.push_back(&(*iter));
		}
		else
		{
			// 兑换券商城
			if ((*iter).type == en_AT_RealObject)
				lstTempGoods.push_back(&(*iter));
		}
	}
	uint32 size = lstTempGoods.size();
	if (0 == size)
		return 0;
	allPage = (size + number - 1) / number;
	if (allPage < page)
		return 0;
	uint32 count = 0;
	std::list<GameGoods*>::iterator ii, endii = lstTempGoods.end();
	for(ii = lstTempGoods.begin(); ii != endii; ++ ii)
	{
		if (++count > upperLimit)
			break;
		if (count > lowerLimit)
		{
			pGoodsList->push_back(*ii);
		}
	}
	return allPage;
}

bool	GameGoodsManager::BuyGoods(const uint32 &serial, const uint32 &goodsId, const uint32 &number)
{
	CharPtr pChr = sCharMgr.getByHandle(serial);
	if (pChr.isNull())
		return false;
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if (pUser.isNull())
		return false;
	WSSocketPtr pSocket = pChr->getSocket();
	if (pSocket.isNull())
		return false;
	
	AICreatureBaseInterface *pAiChrInfe = TO_CREATURE_BASE_INTERFACE(pChr->getAIInterface());
	if (!pAiChrInfe)
		return false;
	const GameGoods *pGoods = GetGameGoodsById(goodsId);
	if (pGoods == NULL)
		return false;	
	uint32 need_gold = pGoods->price * number;
	// 记录日志
	if (!sGLMgr.reduceItemNum(pChr, ItemModel_Money, need_gold))
	{// 扣除元宝		
		return false;
	}
	// 模式号
	uint32 modelId = pGoods->model_id;
	sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_Gateway_Buy, ItemModel_Money, en_UNT_Reduce, need_gold, goodsId, modelId);
	
	// 购买的数量
	uint32 addNum = number;
	WorldPacket packet;	
	if (pGoods->type == en_AT_Common)
	{// 一般商品
		addNum *= pGoods->num;
	}
	else if (pGoods->type == en_AT_Medal)
	{// 勋章
		uint32 curTime = time(0);
		// vip卡ID
		VIPCard vipCard = sVipCardMgr.GetVipCard(modelId);
		if (0 == vipCard.id)
			return false;
		// 是否可购买更多			
		if ((vipCard.flag & en_VipFlag_NoMore) && 
			sVipCardMgr.HaveVIPCard(pChr, modelId))
			return false;
		if (vipCard.type == en_VipType_Body)
		{// 形象
			uint32 bodyid = vipCard.money;
			pAiChrInfe->AddCreatureBody(bodyid, curTime + (vipCard.days*60*60*24));
			pChr->setUInt32Field("id", bodyid);
			if (sProtocolsMgr.CreateBodyListPacket(&packet, pChr))
				sGLMgr.SendProtocolsToChr(pChr, &packet);
			vipCard.money = 0;
			vipCard.coins *= number;
		}
		else
		{
			vipCard.coins *= number;
			vipCard.money *=number;
			vipCard.days *= number;
			vipCard.morraNum *= number;
			pAiChrInfe->AddNewVIPInfo(vipCard);
		}
		//********************乐码相关*******************************//
		if(modelId >= 551 && modelId <= 576)	//打折会员
		{			
			uint32 exchange_id = 0;
			uint32 pid = pUser->getUInt32Field("platform_id");
			uint32 count = sItemMgr.getExchangeDBCount(" (source = %u and data3 = 0 and status = %u)",
												pid,enExchangeStataus_YanZheng);
			if(count)
			{
				std::list<GameExchange> exchanges;
				sItemMgr.getExchangeListDB(&exchanges,0,count,"(source = %u and data3 = 0 and status = %u)",
													pid,enExchangeStataus_YanZheng);
				
				if(exchanges.size())
				{
					GameExchange gameEx = exchanges.front();
					exchange_id = gameEx.exchange_id;
					gameEx.status = enExchangeStataus_Exchaned;
					gameEx.token_user = pid;
					gameEx.token_time = sTools.GetCurDateTime();
					sItemMgr.updateExchangeDB(&gameEx);
					
					WSSocketPtr socket = pChr->getSocket();
					if(!socket.isNull() && sProtocolsMgr.CreateLeCardsStatusPacket(&packet,gameEx.exchange_id,gameEx.status))
						socket->SendPacket(&packet);
				}
			}
			else	//还原为普通的VIP数据
			{
				modelId = 500 + modelId % 10;
				vipCard = sVipCardMgr.GetVipCard(modelId);
				vipCard.coins *= number;
				vipCard.money *=number;
				vipCard.days *= number;
				vipCard.morraNum *= number;
				Log.Notice("script_process_world_game_command_userbuyitems","char[%u] buy error lema item!",pChr->getHandle());
			}
			
			//使用日志
			sBankMgr.LeMaOpLog(pid,en_LMOM_Use,exchange_id,modelId);
			sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_Gateway_Buy, modelId, en_UNT_Add,number,exchange_id);
		}
		//********************乐码相关*******************************//		
		uint32 give_luckyEndTime = sXmlDataMgr.GetConfXMLValue("BUTVIP_GIVELUCKY_CARD_ENDTIME");
		if(!give_luckyEndTime || (give_luckyEndTime && give_luckyEndTime >= time(0)))	//充值送财神卡 活动开关
		{
			if(!sTools.IsSameDate(pAiChrInfe->GetXMLData("USERBUYVIP_TIME"),curTime))
			{
				uint32 random_num = RandomUInt(100);
				uint32 lucky_model = ItemModel_Luck;
				if(random_num >= sXmlDataMgr.GetConfXMLValue("SUPER_LUCKY_PERCENT"))	//送超级幸运卡
				{
					lucky_model = ItemModel_Luck3;
				}
				else if(random_num >= sXmlDataMgr.GetConfXMLValue("BIG_LUCKY_PERCENT"))	//送大幸运卡
				{
					lucky_model = ItemModel_Luck2;
				}
				
				ItemModelPtr modelPtr = sItemModelMgr.getByHandle(lucky_model);
				if(!modelPtr.isNull())
				{
					sGLMgr.addItemNum(pChr,lucky_model,1);
					sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_Hortation, lucky_model, en_UNT_Add,1,en_HSI_UserBuy);
					char msg[256] = "";
					sprintf(msg,sMsg.getMessage("BUYGIFT_MSG1").c_str(),modelPtr->getStringField("name").c_str(),1);
					WSSocketPtr socket = pChr->getSocket();							
					if(!socket.isNull() && sProtocolsMgr.CreateLocalMessagePacket(&packet, msg, sMsg.getType("BUYGIFT_MSG1")))
						socket->SendPacket(&packet);
				}
			}
		}
		
		pAiChrInfe->SetXMLData("USERBUYVIP_TIME",curTime);
		pChr->SaveDB();
		
		if (vipCard.type == en_VipType_FirstBuy)
		{// 作首充标记
			sBankMgr.AddPublicData(pUser, en_PublicData_FirstBuy, addNum, en_ST_Gateway_Buy);
			sBankMgr.SetPublicData(pUser, en_PublicData_FirstBuyTimer, curTime);
			WSSocketPtr socket = pChr->getSocket();
			if (!socket.isNull() && sProtocolsMgr.CreateTellToDoPacket(&packet, en_RemindType_CloseFirstBuy))
				socket->SendPacket(&packet);
		}
		
		if(vipCard.coins)
		{
			addNum = vipCard.coins;
			modelId = ItemModel_Coins;					
		}
		else
		{
			modelId = ItemModel_Golds;
			addNum = vipCard.money;
		}
		// Log.Error("111", "555");
	}
	else if (pGoods->type == en_AT_Prop)
	{// 道具
	
	}
	else if (pGoods->type == en_AT_Character)
	{// 角色类
		
	}
	else if (pGoods->type == en_AT_RealObject)
	{// 实物兑换
	
	}
	// Log.Error("111", "666");
	// 添加物品
	sGLMgr.addItemNum(pChr, modelId, addNum);
	// 记录日志
	sLogDataMgr.UpdateItemsByUserBuyLog(pChr, modelId, addNum);
	// 系统消息
	String str = "恭喜您在【%s】成功购买商品【%u个%s】,消耗【%u元宝】!";	
	if (!StringUtil::checkStringUTF8(str))
	{
		str = StringUtil::StringToUTF8(str);
	}
	char pstr[512] = "";
	sprintf(pstr, str.c_str(), sTools.GetCurDateTime().c_str(), number, pGoods->name.c_str(), need_gold);
	sGLMgr.SendSystemMessage(pChr, pstr);
	// Log.Error("111", "777");
	return true;
}

